package com.example.restatr.Atcivity.Main.Fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.example.restatr.Adapter.NewsListAdapter;
import com.example.restatr.Atcivity.ContentAt;
import com.example.restatr.Atcivity.ActivityManager.HuoDongAt;
import com.example.restatr.Atcivity.GarbageClassification.GarbageClassificationAt;
import com.example.restatr.Atcivity.LivePayment.LivePaymentAt;
import com.example.restatr.Atcivity.ActivityManager.ActivityBean;
import com.example.restatr.Bean.NewsBean;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.example.restatr.Atcivity.NewsAt;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NewsFragment extends Fragment {
    private List<Integer> end = new ArrayList<>();
    private RecyclerView XwList;
    private LinearLayout zzc;
    private NewsListAdapter xwListAdapter;
    private ArrayList<NewsBean.RowsBean> objects = new ArrayList<>();

    private List<ActivityBean.RowsBean> rowsBeans = new ArrayList<>();//活动bean类
    private int PagerNum;
    private TextView bottomText;

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate( R.layout.fragment_xw, container, false );
        XwList = view.findViewById( R.id.XwList );
        zzc = view.findViewById( R.id.zzc );
        bottomText = view.findViewById( R.id.bottomText );
        XwList.setLayoutManager( new LinearLayoutManager( getActivity() ) );
        PagerNum = 1;
        if (MainActivity.info != null && MainActivity.info.equals( "hd" )) {
            bottomText.setVisibility( View.VISIBLE );
            //滑动监听事件，当滑动到底部且停止滑动时，页数加1，并获取数据
            XwList.addOnScrollListener( new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged( recyclerView, newState );
                    if (!recyclerView.canScrollVertically( 1 ) && newState == 0) {
                        PagerNum++;
                        getHdInfo();

                    }
                }
            } );
        }
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint( isVisibleToUser );
        if (isVisibleToUser) {
            objects.clear();
            if (MainActivity.info == null) {
                getXwInfo( "/prod-api/press/press/list?type=", "", HomeFragment.tabId.get( HomeFragment.XwPager.getCurrentItem() ), "/prod-api/press/press/like/" );
            } else {
                switch (MainActivity.info) {
                    case "dj":
                    case "dt":
                    case "tcc":
                        getXwInfo( NewsAt.NewsLink, "", NewsAt.tabId.get( NewsAt.XwPager.getCurrentItem() ), NewsAt.LikeLink );
                        break;
                    case "sh":
                        getXwInfo( "/prod-api/api/living/press/press/list?type=", "", LivePaymentAt.tabId.get( LivePaymentAt.XwPager.getCurrentItem() ), "/prod-api/api/living/press/press/like/" );
                        break;
                    case "lj":
                        getXwInfo( "/prod-api/api/garbage-classification/news/list?type=", MainActivity.sp.getString( "token", "" ), GarbageClassificationAt.tabId.get( GarbageClassificationAt.vp.getCurrentItem() ), "" );
                        break;
                    case "hd":
                        getHdInfo();
                        break;
                }
            }
            Log.d( "TAG", "setUserVisibleHint: " + MainActivity.info );
        }
    }


    private void getXwInfo(final String link, String token, final String id, String likeLink) {
        new Thread( new Runnable() {
            @Override
            public void run() {
                final String get = Tools.Get( link + id, token );
                if (get != null & getActivity() != null) {
                    getActivity().runOnUiThread( new Runnable() {
                        @Override
                        public void run() {
                            //新闻Bean类
                            NewsBean newsBean = new Gson().fromJson( get, NewsBean.class );
                            objects.addAll( newsBean.getRows() );
                            xwListAdapter = new NewsListAdapter( getActivity(), objects, likeLink );
                            xwListAdapter.setXwListAdapter( xwListAdapter );
                            XwList.setAdapter( xwListAdapter );
                            zzc.setVisibility( View.GONE );
                            //为新闻内容图片拼接URL
                            for (int i = 0; i < objects.size(); i++) {
                                end.clear();
                                Matcher matcher = Pattern.compile( "<img src=\"" ).matcher( objects.get( i ).getContent() );
                                while (matcher.find()) {
                                    end.add( matcher.end() );
                                }
                                int addLength = 0;
                                for (int j = 0; j < end.size(); j++) {
                                    objects.get( i ).getContent().insert( end.get( j ) + addLength, Tools.ip );
                                    addLength += Tools.ip.length();
                                }
                            }

                        }
                    } );
                }

            }
        } ).start();
    }

    //获取活动列表
    private void getHdInfo() {
        new Thread( () -> {
            //分页获取活动列表，每次获取2个
            ActivityBean activityBean = new Gson().fromJson( Tools.Get( "/prod-api/api/activity/activity/list?categoryId="
                    + HuoDongAt.themeId.get( HuoDongAt.XwPager.getCurrentItem() ) +
                    "&pageNum=" + PagerNum + "&pageSize=2", "" ), ActivityBean.class );
            int total = activityBean.getTotal();
            //获取新闻总数，当集合大小小于新闻总数时把数据添加进集合中
            if (rowsBeans.size() < total) {
                rowsBeans.addAll( activityBean.getRows() );
                Log.d( "TAG", "getHdInfo: "+rowsBeans.size() );
                if (getActivity() != null) {
                    getActivity().runOnUiThread( () -> {
                        if (rowsBeans.size() == total) {
                            bottomText.setText( "——到底了——" );
                        }
                        zzc.setVisibility( View.GONE );
                        XwList.setAdapter( new AllAdapter() );
                    } );
                }
            }
        } ).start();
    }


    //活动适配器
    class AllAdapter extends RecyclerView.Adapter<AllAdapter.AllActivityViewHolder> {


        @NonNull
        @Override
        public AllActivityViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from( getActivity() ).inflate( R.layout.xw_card_item, parent, false );
            return new AllActivityViewHolder( inflate );
        }

        @Override
        public void onBindViewHolder(@NonNull AllActivityViewHolder holder, int position) {
            Glide.with( getActivity() )
                    .load( Tools.ip + rowsBeans.get( position ).getImgUrl() )
                    .transform( new RoundedCorners( 15 ) )
                    .into( holder.tp );
            holder.title.setText( rowsBeans.get( position ).getName() );
            holder.date.setText( rowsBeans.get( position ).getPublishTime().substring( 0, 10 ) );
            holder.likeNum.setText( String.valueOf( rowsBeans.get( position ).getLikeNum() ) );
            holder.ReadNum.setText( String.valueOf( rowsBeans.get( position ).getSignupNum() ) );
            final boolean[] isLike = {false};
            final boolean[] isSignup = {false};

            //item点击事件
            holder.Rl.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent( getActivity(), ContentAt.class );
                    intent.putExtra( "title", rowsBeans.get( position ).getName() );
                    intent.putExtra( "content", rowsBeans.get( position ).getContent() );
                    intent.putExtra( "id", rowsBeans.get( position ).getId() );
                    intent.putExtra( "date", rowsBeans.get( position ).getPublishTime() );
                    intent.putExtra( "likeNum", rowsBeans.get( position ).getLikeNum() );
                    intent.putExtra( "ReadNum", rowsBeans.get( position ).getSignupNum() );
                    intent.putExtra( "commentNum", holder.commentNum.getText().toString() );
                    intent.putExtra( "isLike", isLike[0] );
                    intent.putExtra( "type", "Hd" );
                    intent.putExtra( "isSingUp", isSignup[0] );
                    startActivityForResult( intent, 1 );
                }
            } );
            //点赞点击事件
            holder.dianz.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //判断是否为已点赞
                    if (!isLike[0]) {
                        rowsBeans.get( position ).setLikeNum( rowsBeans.get( position ).getLikeNum() + 1 );
                        holder.likeNum.setText( String.valueOf( rowsBeans.get( position ).getLikeNum() ) );
                        holder.likeImage.setImageResource( R.drawable.ic_baseline_favorite_24 );
                        isLike[0] = true;
                    } else {
                        rowsBeans.get( position ).setLikeNum( rowsBeans.get( position ).getLikeNum() - 1 );
                        holder.likeNum.setText( String.valueOf( rowsBeans.get( position ).getLikeNum() ) );
                        holder.likeImage.setImageResource( R.drawable.ic_baseline_favorite_border_24 );
                        isLike[0] = false;
                    }
                }
            } );
            new Thread( () -> {
                try {
                    //判断是否报名该活动
                    String token = Tools.Get( "/prod-api/api/activity/signup/check?activityId=" + rowsBeans.get( position ).getId(),
                            MainActivity.sp.getString( "token", "" ) );
                    //获取评论数
                    String get = Tools.Get( "/prod-api/api/activity/comment/number?activityId=" + rowsBeans.get( position ).getId(),
                            MainActivity.sp.getString( "token", "" ) );
                    JSONObject jx = new JSONObject( token );
                    JSONObject jx2 = new JSONObject( get );
                    isSignup[0] = jx.getBoolean( "isSignup" );
                    String commentNum = jx2.getString( "commentNum" );
                    if (getActivity() != null) {
                        getActivity().runOnUiThread( new Runnable() {
                            @Override
                            public void run() {
                                if (isSignup[0]) {
                                    holder.readImg.setImageResource( R.drawable.ic_round_select_person_add_24 );
                                } else {
                                    holder.readImg.setImageResource( R.drawable.ic_round_person_add_24 );
                                }
                                holder.commentNum.setText( commentNum );
                            }
                        } );
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } ).start();
        }

        @Override
        public int getItemCount() {
            return rowsBeans.size();
        }

        class AllActivityViewHolder extends RecyclerView.ViewHolder {
            private CardView Rl;
            private TextView title;
            private ImageView tp;
            private TextView date;
            private LinearLayout dianz;
            private ImageView likeImage;
            private TextView likeNum;
            private TextView ReadNum;
            private ImageView readImg;
            private TextView commentNum;
            private LinearLayout readLL;
            private LinearLayout commentLL;


            public AllActivityViewHolder(@NonNull View itemView) {
                super( itemView );
                Rl = itemView.findViewById( R.id.Rl );
                title = itemView.findViewById( R.id.title );
                tp = itemView.findViewById( R.id.tp );
                date = itemView.findViewById( R.id.date );
                dianz = itemView.findViewById( R.id.dianz );
                likeImage = itemView.findViewById( R.id.likeImage );
                likeNum = itemView.findViewById( R.id.likeNum );
                ReadNum = itemView.findViewById( R.id.ReadNum );
                commentNum = itemView.findViewById( R.id.commentNum );
                readImg = itemView.findViewById( R.id.readImg );
                readLL = itemView.findViewById( R.id.read_LL );
                commentLL = itemView.findViewById( R.id.comment_LL );

            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult( requestCode, resultCode, data );
        rowsBeans.clear();
        PagerNum=1;
        getHdInfo();
    }
}